package com.touzhijia.authority.security;

import lombok.Getter;
import lombok.ToString;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 作者： lzw<br/>
 * 创建时间：2018-03-15 12:58 <br/>
 */
@ToString(exclude = {"userDetails"})
@Getter
public class UserLoginToken extends AbstractAuthenticationToken {

    private String username;
    private String password;
    private String captcha;
    private UserDetails userDetails;

    /**
     * 用于创建登录的凭证信息
     */
    public UserLoginToken(String username, String password, String captcha) {
        super(null);
        this.username = username;
        this.password = password;
        this.captcha = captcha;
        setAuthenticated(false);
    }

    /**
     * 用于创建登录成功的用户信息
     */
    public UserLoginToken(UserDetails userDetails) {
        super(userDetails.getAuthorities());
        this.username = userDetails.getUsername();
        this.password = userDetails.getPassword();
        this.userDetails = userDetails;
        super.setAuthenticated(true);
    }

    /**
     * username 用户名
     */
    @Override
    public Object getCredentials() {
        return password;
    }

    /**
     * password 密码
     */
    @Override
    public Object getPrincipal() {
        return username;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        password = null;
        captcha = null;
    }
}
